package com.qf.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.entity.User;
import com.qf.entity.UserDTO;
import com.qf.service.UserService;
import com.qf.util.JwtUtils;
import com.qf.util.R;
import com.qf.util.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisUtil redisUtil;
    @PostMapping("/user/login")
    public R login(@RequestBody User user){
        String token=userService.login(user);
        return R.success(token);
    }
    //查全部
    //分页查
    //模糊搜索
    @GetMapping("/user/list")
    @PreAuthorize("hasAuthority('system:user:list')")
    public R list(UserDTO userDTO){
        log.info("分页参数:{},{}",userDTO);
        PageHelper.startPage(userDTO.getPageNum(),userDTO.getPageSize());
        List<User> list = userService.list(userDTO);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return R.success(pageInfo);
    }
    //删除单条
    @GetMapping("/user/delete")
    @PreAuthorize("hasAuthority('system:user:del')")
    public R deleteById(int id){
        userService.deleteById(id);
        return R.success();
    }
    @GetMapping("/user/deleteAll")
    @PreAuthorize("hasAuthority('system:user:del')")
    public R deleteAll(@RequestParam List<Integer> id){
        userService.deleteAll(id);
        return R.success();
    }
    @PostMapping("/user/add")
    @PreAuthorize("hasAuthority('system:user:add')")
    public R addUser(@RequestBody User user){
        userService.addUser(user);
        return R.success();
    }
    @PostMapping("/user/update")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public R updateUser(@RequestBody User user){
        userService.updateUser(user);
        return R.success();
    }
    //退出功能需要清空token
    @PostMapping("/user/logout")
    public R logout(@RequestBody Map<String,String> map){
        String token=map.get("token");
        Claims claims=jwtUtils.parseJwt(token);
        Object uuid = claims.get("uuid");
        //得到uuid后清除token
        redisUtil.deleteObject("user:key:"+uuid);
        return R.success();
    }
}
